package cn.bone.search.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.gson.GsonBuilder;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.apache.http.HttpHost;
import org.springframework.boot.autoconfigure.elasticsearch.jest.JestProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by superbone on 2017/3/13.
 */
@Configuration
public class Config {

    @Resource
    private DataSourceProperties dbProperties;

    @Bean
    public DataSource dataSource(){

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dbProperties.getUrl());
        dataSource.setDriverClassName(dbProperties.getDriverClassName());
        dataSource.setUsername(dbProperties.getUsername());
        dataSource.setPassword(dbProperties.getPassword());

        try {
            dataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 手动配置jest
     * @return
     */
    @Resource
    private JestProperties jestProperties;
    @Bean
    public JestClient jestClient(){
        JestClientFactory factory = new JestClientFactory();
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
                jestProperties.getUris());
        if (StringUtils.hasText(jestProperties.getUsername())) {
            builder.defaultCredentials(jestProperties.getUsername(),
                    jestProperties.getPassword());
        }
        String proxyHost = jestProperties.getProxy().getHost();
        if (StringUtils.hasText(proxyHost)) {
            Integer proxyPort = jestProperties.getProxy().getPort();
            Assert.notNull(proxyPort, "Proxy port must not be null");
            builder.proxy(new HttpHost(proxyHost, proxyPort));
        }
        HttpClientConfig config = builder.gson(
                new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create())
                .connTimeout(1500)
                .readTimeout(3000)
                .multiThreaded(true)
                .build();

        factory.setHttpClientConfig(config);
        JestClient client = factory.getObject();
        return client;
    }
}
